from Exceptions import SemanticException
from Exceptions import UndefinedNameException, RedeclarationException, RedefinitionException, ValueTypeException
from pyparsing import *

#Context aware parser
class FSPSymbol(Regex):
  def __init__(self, pattern, FSPType, namespace, flags=0):
    super(FSPSymbol, self).__init__(pattern, flags)
    self.namespace = namespace
    self.FSPType = FSPType
    self.errmsg = self.FSPType + " {name} is not defined in namespace " + self.namespace.name
  def parseImpl(self, instring, loc, doActions=True):
    (loc,ret) = super(FSPSymbol, self).parseImpl(instring, loc, doActions)
    try:
      ret = self.namespace.getName(instring, loc, ret[0], self.FSPType)
    #except SemanticException:
    #  raise ParseException(instring, loc, self.errmsg.format(name=ret[0]), self)
    except UndefinedNameException:
      raise ParseException(instring, loc, "UNDEFINED_NAME", self)
    except RedeclarationException:
      raise ParseException(instring, loc, "REDECLARATION", self)
    except RedefinitionException:
      raise ParseException(instring, loc, "REDEFINITION", self)
    except ValueTypeException:
      raise ParseException(instring, loc, "VALUE_TYPE", self)
    return loc, ret
  def __str__(self):
    try:
      return super(FSPSymbol, self).__str__()
    except:
      pass
    if self.strRepr is None:
      self.strRepr = "Symbol:(%s)" % repr(self.pattern)
    return self.strRepr
